<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="800px"
    destroy-on-close
    @close="handleClose"
  >
    <div class="video-player-container">
      <video
        v-if="videoUrl"
        ref="videoRef"
        :src="videoUrl"
        controls
        autoplay
        class="video-player"
        @error="onError"
      >
        您的浏览器不支持视频播放
      </video>
      <div v-else class="no-video">
        <el-empty description="暂无视频" />
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { ElDialog, ElEmpty } from "element-plus";
import { useMessage } from "@/hooks/useMessage";

interface Props {
  modelValue: boolean;
  videoUrl?: string;
  title?: string;
}

interface Emits {
  (e: "update:modelValue", value: boolean): void;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  videoUrl: "",
  title: "视频播放",
});

const emit = defineEmits<Emits>();
const msg = useMessage();

const visible = ref(props.modelValue);
const videoRef = ref<HTMLVideoElement>();

// 监听外部传入的值变化
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
  }
);

// 监听内部值变化并同步到外部
watch(visible, (val) => {
  emit("update:modelValue", val);
});

const handleClose = () => {
  // 暂停视频播放
  if (videoRef.value) {
    videoRef.value.pause();
    videoRef.value.currentTime = 0;
  }
  visible.value = false;
};

const onError = (error: Event) => {
  console.error("视频加载失败:", error);
  msg.error("视频加载失败，请检查文件是否存在");
};
</script>

<style scoped lang="scss">
.video-player-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background-color: #000;
  border-radius: 4px;

  .video-player {
    width: 100%;
    max-height: 600px;
    outline: none;
  }

  .no-video {
    width: 100%;
    height: 400px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f5f5;
  }
}
</style>

